#############################################################################
#Yuhua Wang#
#The Rise and Fall of Imperial China: The Social Origins of State Development#
#Princeton University Press, 2022#
############################################################################

############################################################################
#Chapter 4#
############################################################################


######################################
#Figure 4.1: Number of Households by Region (0–1200)#
######################################

rm(list = ls())
library(foreign)
library(tidyverse)

library(ggrepel) 
library(plyr)
require(scales)
require(gridExtra)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

householdbyregion <- read.dta("household shortperiod for R.dta")

householdbyregion$treatment <- as.factor(householdbyregion$regionid)

householdtangsong <- ggplot(householdbyregion[!is.na(householdbyregion$household),], aes(year,household,group=treatment,color=treatment,linetype=treatment),show.legend = F) + 
  geom_point(show.legend = F) +
  geom_line(size=1,show.legend = F)+
  scale_x_continuous(name="Year", limits=c(-10,1900), breaks=c(0,200,400,600,800,1000,1200)) +
  scale_y_continuous(name="Households (millions)", limits=c(0,8),breaks=c(0,2,4,6,8))+
  theme(legend.position="none")+
  theme_bw()+
  annotate(geom="text", x = 1520, y=5.4, label = "Middle Yangtze",size=3,fontface =2)+
  annotate(geom="text", x = 1490, y=4.3, label = "North China", size=3,fontface =2)+
  annotate(geom="text", x = 1515, y=3.7, label = "Lower Yangtze", size=3,fontface =2)+
  annotate(geom="text", x = 1520, y=2.9, label = "Upper Yangtze", size=3,fontface =2)+
  annotate(geom="text", x = 1540, y=2.2, label = "Southeast China", size=3,fontface =2)+
  annotate(geom="text", x = 1540, y=1.75, label = "Northeast China", size=3,fontface =2)+
  annotate(geom="text", x = 1460, y=0.8, label = "Lingnan", size=3,fontface =2)

householdtangsong

######################################
#Figure 4.2: Locations of Major Officials’ Hometowns in Tang and Song#
######################################

#Constructed using QGIS#

######################################
#Figure 4.3: Major Officials’ Kinship Networks in Tang and Song#
######################################

######################################
#(a) Elite Social Terrain in the Late Tang Era (779–805)#
######################################

rm(list = ls())
library(foreign) 
library(ggplot2) 
require(ggplot2)
library(ggrepel) 
library(plyr)
require(scales)
library(igraph)
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

set.seed(12349)

#read in egelist
rawedgestang<-read.csv("tang edgelist.csv")

#turn edgelist into adjacency matrix
matrixtang <-as.matrix(get.adjacency(graph.data.frame(rawedgestang)))

#write in a csv file
write.csv(matrixtang,"tang adjmatrix.csv", row.names = FALSE)

# detach igraph package
detach("package:igraph")

#Read in Adjacency Matrix

net.adj.tang <- as.matrix(matrixtang) 

# load in vertex attributes

#orignal coordinates
nodeInfoTang <- read.csv(file="tang vertex.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.tang) # peek at matrix 
print(nodeInfoTang)  # peek at attribute data

# create undirected network object from matrix

net_tang<-network(net.adj.tang, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_tang)

# ATTACHING VERTEX ATTRIBUTES

# load in other attributes 
net_tang%v%"lon" <- nodeInfoTang$X
net_tang%v%"lat" <- nodeInfoTang$Y
net_tang%v%"name" <- nodeInfoTang$name_pinyin
net_tang%v%"ego" <- nodeInfoTang$ego


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_tang)

summary(net_tang)

gden(net_tang)

deg <- degree(net_tang,gmode="graph")

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

# Add Tang map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

#Shapefile#

tang <- importShapefile("_tang_with_provinces_r9w.shp")

proj.abbr <- attr(tang, "projection")

plotPolys(tang, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Network on map

plot.network(net_tang,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_tang%v%"lon",net_tang%v%"lat"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             vertex.cex=rescale(deg,1,6),
             vertex.col="darkred",
             usecurve=TRUE,
             edge.col="grey",
             edge.curve = 0.01,
             # please don't jitter the points around
             jitter=FALSE)


######################################
#(b) Elite Social Terrain in the Early Song Era (997–1022)#
######################################

rm(list = ls())

library(statnet)
library("network")
library(igraph)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

set.seed(12349)

#Constructing adj matrix of Zhenzong (997-1022) officials

#read in egelist of officials with kinship ties

Sys.setlocale(locale = "en_us.UTF-8")
edge.list.woisolates <- read.table("zhenzong officials and kin edgelist.csv",
                                   sep=",",
                                   header=TRUE, 
                                   encoding="UTF-8", 
                                   stringsAsFactors=FALSE)

## plot edge-list data
graph.woisolates <- graph.data.frame(edge.list.woisolates, directed=FALSE) 

plot(graph.woisolates,vertex.cex=0.01)

## convert to adjacency list
adj.zhenzong.woisolates<- get.adjacency(graph.woisolates, type="both") 

## convert to matrix
matrix.zhenzong.woisolates <- as.matrix(adj.zhenzong.woisolates) 

##output as csv file
write.csv(matrix.zhenzong.woisolates,file="adjmatrix_zhenzong_woisolates.csv")

#delete the first row and first column with the ids and save as adjmatrix_zhenzong.csv

# detach igraph package
detach("package:igraph")

# read in the adjacency matrix and convert to matrix
net.adj.zhenzong<-read.csv(file="adjmatrix_zhenzong.csv",header=FALSE,stringsAsFactors=FALSE)
net.adj.zhenzong <- as.matrix(net.adj.zhenzong) 

# load in vertex attributes (make sure the sequence conform to the adjacency matrix)
nodeInfozhenzong <- read.csv(file="Zhenzong vertex attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.zhenzong) # peek at matrix 
print(nodeInfozhenzong)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.zhenzong) <- nodeInfozhenzong$name_pinyin
colnames(net.adj.zhenzong) <- nodeInfozhenzong$name_pinyin

print(net.adj.zhenzong)

# create undirected network object from matrix

net_official_zhenzong<-network(net.adj.zhenzong, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_official_zhenzong)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_official_zhenzong%v%'vertex.names'<- nodeInfozhenzong$name_pinyin

# load in other attributes #NOT DONE YET
net_official_zhenzong%v%"x" <- nodeInfozhenzong$x
net_official_zhenzong%v%"y" <- nodeInfozhenzong$y


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_official_zhenzong)

summary(net_official_zhenzong)

# centrality measures

deg_zhenzong<-degree(net_official_zhenzong,gmode="graph")
deg_zhenzong

deg_zhenzong.data<-data.frame(deg_zhenzong)
deg_zhenzong.data


# graph for all the Zhenzong officials

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

op<-par(mar=c(0,0,0,0))
plot(net_official_zhenzong,vertex.col="#DF536B", vertex.cex=rescale(deg_zhenzong,0.5,3))
par(op)

# Add Northern Song map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

#Set colors#

t_col <- function(color, percent = 50, name = NULL) {
  #      color = color name
  #    percent = % transparency
  #       name = an optional name for the color
  
  ## Get RGB values for named color
  rgb.val <- col2rgb(color)
  
  ## Make new color using input color as base and alpha set by transparency
  t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],
               max = 255,
               alpha = (100 - percent) * 255 / 100,
               names = name)
  
  ## Save the color
  invisible(t.col)
}
## END

mycol <- t_col("lightgrey", perc = 50, name = "lt.grey")

#Shapefile#

song <- importShapefile("Northern Song borders.shp")

proj.abbr <- attr(song, "projection")

plotPolys(song, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Network on map

plot.network(net_official_zhenzong,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_official_zhenzong%v%"x",net_official_zhenzong%v%"y"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             mode = "fruchtermanreingold",
             vertex.col="red",
             vertex.cex=rescale(deg_zhenzong,0.5,4),
             edge.col=mycol,
             edge.lwd=0.01,
             usecurve=FALSE,
             # please don't jitter the points around
             jitter=FALSE)


############################################
#(c) Elite Social Terrain in the Mid-Song Era (1067–1085)#
############################################

rm(list = ls())

library(statnet)
library("network")
library(igraph)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

set.seed(12350)

#Constructing adj matrix of Shenzong (1067-1085) officials

#read in egelist of officials with kinship ties

Sys.setlocale(locale = "en_us.UTF-8")
edge.list.woisolates <- read.table("shenzong officials and kin edgelist.csv",
                                   sep=",",
                                   header=TRUE, 
                                   encoding="UTF-8", 
                                   stringsAsFactors=FALSE)

## plot edge-list data
graph.woisolates <- graph.data.frame(edge.list.woisolates, directed=FALSE) 

plot(graph.woisolates,vertex.cex=0.01)

## convert to adjacency list
adj.shenzong.woisolates<- get.adjacency(graph.woisolates, type="both") 

## convert to matrix
matrix.shenzong.woisolates <- as.matrix(adj.shenzong.woisolates) 


##output as csv file
write.csv(matrix.shenzong.woisolates,file="adjmatrix_shenzong_woisolates.csv")

#delete the first row and first column with the ids and save as adjmatrix_shenzong.csv

# detach igraph package
detach("package:igraph")

# read in the adjacency matrix and convert to matrix
net.adj.shenzong<-read.csv(file="adjmatrix_shenzong.csv",header=FALSE,stringsAsFactors=FALSE)
net.adj.shenzong <- as.matrix(net.adj.shenzong) 

# load in vertex attributes (make sure the sequence conform to the adjacency matrix)
nodeInfoshenzong <- read.csv(file="Shenzong vertex attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.shenzong) # peek at matrix 
print(nodeInfoshenzong)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.shenzong) <- nodeInfoshenzong$name_pinyin
colnames(net.adj.shenzong) <- nodeInfoshenzong$name_pinyin

print(net.adj.shenzong)

# create undirected network object from matrix

net_official_shenzong<-network(net.adj.shenzong, directed=FALSE, matrix.type="adjacency")


# it read in vertex names from matrix col names ...
network.vertex.names(net_official_shenzong)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_official_shenzong%v%'vertex.names'<- nodeInfoshenzong$name_pinyin

# load in other attributes #NOT DONE YET
net_official_shenzong%v%"x" <- nodeInfoshenzong$x
net_official_shenzong%v%"y" <- nodeInfoshenzong$y


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_official_shenzong)

summary(net_official_shenzong)


# centrality measures

deg_shenzong<-degree(net_official_shenzong,gmode="graph")
deg_shenzong

deg_shenzong.data<-data.frame(deg_shenzong)
deg_shenzong.data


# graph for all the shenzong officials

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

op<-par(mar=c(0,0,0,0))
plot(net_official_shenzong,vertex.col="#DF536B", vertex.cex=rescale(deg_shenzong,0.5,3))
par(op)


# Add Northern Song map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

#Set color#

t_col <- function(color, percent = 50, name = NULL) {
  #      color = color name
  #    percent = % transparency
  #       name = an optional name for the color
  
  ## Get RGB values for named color
  rgb.val <- col2rgb(color)
  
  ## Make new color using input color as base and alpha set by transparency
  t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],
               max = 255,
               alpha = (100 - percent) * 255 / 100,
               names = name)
  
  ## Save the color
  invisible(t.col)
}
## END

mycol <- t_col("lightgrey", perc = 50, name = "lt.grey")

#Shapefile#

song <- importShapefile("Northern Song borders.shp")

proj.abbr <- attr(song, "projection")

plotPolys(song, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Network on map

plot.network(net_official_shenzong,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_official_shenzong%v%"x",net_official_shenzong%v%"y"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             mode = "fruchtermanreingold",
             vertex.col="red",
             vertex.cex=rescale(deg_shenzong,0.5,4),
             edge.col=mycol,
             usecurve=FALSE,
             # please don't jitter the points around
             jitter=FALSE)



######################################
#Figure 4.4: Major Officials’ Marriage Networks in Tang and Song#
######################################

######################################
#(a) Late Tang (750–850)#
######################################

rm(list = ls())
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

set.seed(12349)

#Read in Tackett's Adjacency Matrix

net.adj.tackett<-read.csv(file="adjacency_matrix_tackett.csv",header=FALSE,stringsAsFactors=FALSE)

net.adj.tackett <- as.matrix(net.adj.tackett) 

# load in vertex attributes
nodeInfoTackett <- read.csv(file="vertexAttributesTackett.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.tackett) # peek at matrix 
print(nodeInfoTackett)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.tackett) <- nodeInfoTackett$choronym_surname_no
colnames(net.adj.tackett) <- nodeInfoTackett$choronym_surname_no

print(net.adj.tackett)

# create undirected network object from matrix

net_tackett<-network(net.adj.tackett, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_tackett)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_tackett%v%'vertex.names'<- nodeInfoTackett$choronym_surname_no

# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_tackett)

summary(net_tackett)

gden(net_tackett)

#0.02827965

# centrality measures

deg_tackett<-degree(net_tackett,gmode="graph")
deg_tackett

deg_tackett.data<-data.frame(deg_tackett)
deg_tackett.data

btw_tackett<-betweenness(net_tackett,gmode="graph")
btw_tackett

btw_tackett.data<-data.frame(btw_tackett)
btw_tackett.data

# graphs

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

mycoords1 <- gplot(net_tackett,gmode="graph", vertex.cex=1.5)

op<-par(mar=c(0,0,0,0))
gplot(net_tackett,gmode="graph", coord=mycoords1, vertex.col="#DF536B", 
      vertex.cex=rescale(deg_tackett,0.5,3), edge.col="grey80",suppress.axes=TRUE,
      ylim=c(min(mycoords1[,2])-1,max(mycoords1[,2])+1),
      mode="fruchtermanreingold")
par(op)


##################################################
#The following four graphs are from the same dataset#
#(b) Song Zhenzong (997–1022)
#(c) Song Shenzong (1067–1085)
#(d) Song Ningzong (1194–1224)
#(e) Song Lizong (1224–1264)
##################################################

rm(list = ls())
library(statnet)
library("network")
set.seed(12346)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

#Read in Song Officials' Adjacency Matrix

net.adj.song<-read.csv(file="all song officials adj matrix.csv",header=FALSE,stringsAsFactors=FALSE)

net.adj.song <- as.matrix(net.adj.song) 

# load in vertex attributes
nodeInfosong <- read.csv(file="all song officials vertex attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.song) # peek at matrix 
print(nodeInfosong)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.song) <- nodeInfosong$name_pinyin
colnames(net.adj.song) <- nodeInfosong$name_pinyin

print(net.adj.song)

# create undirected network object from matrix

net_official_song<-network(net.adj.song, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_official_song)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_official_song%v%'vertex.names'<- nodeInfosong$name_pinyin


net_official_song%v%"reign1" <- nodeInfosong$reign1
net_official_song%v%"reign2" <- nodeInfosong$reign2
net_official_song%v%"reign3" <- nodeInfosong$reign3
net_official_song%v%"reign4" <- nodeInfosong$reign4
net_official_song%v%"reign5" <- nodeInfosong$reign5
net_official_song%v%"reign6" <- nodeInfosong$reign6
net_official_song%v%"reign7" <- nodeInfosong$reign7
net_official_song%v%"reign8" <- nodeInfosong$reign8
net_official_song%v%"reign9" <- nodeInfosong$reign9
net_official_song%v%"reign10" <- nodeInfosong$reign10
net_official_song%v%"reign11" <- nodeInfosong$reign11
net_official_song%v%"reign12" <- nodeInfosong$reign12
net_official_song%v%"reign13" <- nodeInfosong$reign13
net_official_song%v%"reign14" <- nodeInfosong$reign14
net_official_song%v%"reign15" <- nodeInfosong$reign15
net_official_song%v%"reign16" <- nodeInfosong$reign16
net_official_song%v%"reign17" <- nodeInfosong$reign17


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_official_song)

summary(net_official_song)

gden(net_official_song)

#0.004011799

# graphs

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}


#Network by reign

#(b) Song Zhenzong (997–1022)#
#reign3	"Zhenzong"
net_songofficial_reign3<-get.inducedSubgraph(net_official_song,eid=which(net_official_song%v%'reign3'==1))

summary(net_songofficial_reign3)
gden_net_songofficial_reign3 <- data.frame(table(gden(net_songofficial_reign3)))
gden(net_songofficial_reign3)

deg_song_r3<-degree(net_songofficial_reign3,gmode="graph")
deg_song_r3

op<-par(mar=c(0,0,0,0))
plot(net_songofficial_reign3,vertex.col="#DF536B", vertex.cex=rescale(deg_song_r3,0.5,3), edge.col="grey80", mode="fruchtermanreingold")
par(op)

#(c) Song Shenzong (1067–1085)#
#reign6	"Shenzong"
net_songofficial_reign6<-get.inducedSubgraph(net_official_song,eid=which(net_official_song%v%'reign6'==1))

summary(net_songofficial_reign6)
gden_net_songofficial_reign6 <- data.frame(table(gden(net_songofficial_reign6)))
gden(net_songofficial_reign6)

deg_song_r6<-degree(net_songofficial_reign6,gmode="graph")
deg_song_r6

op<-par(mar=c(0,0,0,0))
plot(net_songofficial_reign6,vertex.col="#DF536B", vertex.cex=rescale(deg_song_r6,0.5,3), edge.col="grey80", mode="fruchtermanreingold")
par(op)

#(d) Song Ningzong (1194–1224)#
#reign13	"Ningzong"
net_songofficial_reign13<-get.inducedSubgraph(net_official_song,eid=which(net_official_song%v%'reign13'==1))

summary(net_songofficial_reign13)
gden_net_songofficial_reign13 <- data.frame(table(gden(net_songofficial_reign13)))

gden(net_songofficial_reign13)

deg_song_r13<-degree(net_songofficial_reign13,gmode="graph")
deg_song_r13

op<-par(mar=c(0,0,0,0))
plot(net_songofficial_reign13,vertex.col="#DF536B", vertex.cex=rescale(deg_song_r13,0.5,3), edge.col="grey80", mode="fruchtermanreingold")
par(op)


#(e) Song Lizong (1224–1264)#
#reign14	"Lizong"
net_songofficial_reign14<-get.inducedSubgraph(net_official_song,eid=which(net_official_song%v%'reign14'==1))

summary(net_songofficial_reign14)
gden_net_songofficial_reign14 <- data.frame(table(gden(net_songofficial_reign14)))
gden(net_songofficial_reign14)

deg_song_r14<-degree(net_songofficial_reign14,gmode="graph")
deg_song_r14

op<-par(mar=c(0,0,0,0))
plot(net_songofficial_reign14,vertex.col="#DF536B", vertex.cex=rescale(deg_song_r14,0.5,3), edge.col="grey80", mode="fruchtermanreingold")
par(op)




################################
#Figure 4.5: Bureaucratic Recruitment of Major Officials from Tang to Song#
################################

rm(list = ls())
library(foreign)
library(tidyverse)

library(ggrepel) 
library(plyr)
require(scales)
require(gridExtra)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

exam <- read.dta("exam by cohort.dta")

attach(exam)

exam$treatment <- as.factor(exam$treatment)


exambycohort <- ggplot(data=exam, aes(x=start_year,y=exam_aristocrat_percent,group=treatment)) + 
  geom_line(aes(x=start_year, y=exam_percent,linetype="dashed",color="lightred")) +
  geom_line(aes(x=start_year, y=exam_aristocrat_percent,linetype="solid",color="lightblue")) +
  geom_ribbon(aes(ymin=0, ymax=exam$exam_aristocrat_percent), alpha=0.3) +
  geom_ribbon(aes(ymin=0, ymax=exam$exam_percent), alpha=0.1) +
  scale_color_manual(values=c("#F8766D",  "#619CFF"))+
  scale_x_continuous(name="Year of Becoming Major Official", limits=c(610,1260), breaks=c(610,650,690,730,770,810,850,890,930,970,1010,1050,1090,1130,1170,1210,1250)) +
  scale_y_continuous(name="Percentage of All Major Officials (%)",limits=c(0,100), breaks=c(0,10,20,30,40,50,60,70,80,90,100)) +
  geom_vline(xintercept=907, linetype="dashed", 
             color = "grey", size=0.5)+
  geom_vline(xintercept=960, linetype="dashed", 
             color = "grey", size=0.5)+
  geom_vline(xintercept=1127, linetype="dashed", 
             color = "grey", size=0.3)+
  annotate(geom="text", x = 750, y=90, label = "Tang",size=5)+
  annotate(geom="text", x = 930, y=90, label = "Five", size=3)+
  annotate(geom="text", x = 930, y=80, label = "Dynasties", size=3)+
  annotate(geom="text", x = 1130, y=90, label = "Song", size=5)+
  annotate(geom="text", x = 1050, y=80, label = "N", size=4)+
  annotate(geom="text", x = 1210, y=80, label = "S", size=4)+
  annotate(geom="text", x = 1200, y=64, label = "Officials", size=3)+
  annotate(geom="text", x = 1190, y=60, label = "entered through", size=3)+
  annotate(geom="text", x = 1200, y=56, label = "examination", size=3)+
  annotate(geom="text", x = 1090, y=12, label = "Officials of", size=3)+
  annotate(geom="text", x = 1090, y=8, label = "aristocratic descent", size=3)+
  annotate(geom="text", x = 1110, y=4, label = "entered through examination", size=3)+
  theme_bw()+
  theme(legend.position="none")+
  theme(
    axis.title.x = element_text(size = 10),
    axis.text.x = element_text(size = 7),
    axis.text.y = element_text(size = 7),
    axis.title.y = element_text(size = 10))

exambycohort


################################
#Figure 4.6: Major Officials’ Kinship Networks from Tang to Song#
################################

rm(list = ls())
library(foreign)
library(tidyverse)

library(ggrepel) 
library(plyr)
require(scales)
require(gridExtra)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 4/data/")

data <- read.dta("kinproximity_st mean by cohort subsample for R.dta")

attach(data)

data$treatment <- as.factor(data$treatment)


kinproximity <- ggplot(data=data, aes(x=start_year, y=kinproximity_st_mean, group=treatment,color=treatment)) + 
  geom_line() +geom_ribbon(aes(ymin=data$kinproximity_st_min95, ymax=data$kinproximity_st_max95), linetype=2, alpha=0.1) +
  scale_color_manual(values=c("#F8766D",  "#619CFF"))+
  scale_x_continuous(name="Year of Becoming Major Official", limits=c(610,1180), breaks=c(610,650,690,730,770,810,850,890,930,970,1010,1050,1090,1130,1170)) +
  scale_y_continuous(name="Average Kinship Network Localization (-> More Localized)",limits=c(-0.05,0.5), breaks=c(0,0.1,0.2,0.3,0.4,0.5)) +
  geom_vline(xintercept=907, linetype="dashed", 
             color = "grey", size=0.5)+
  geom_vline(xintercept=960, linetype="dashed", 
             color = "grey", size=0.5)+
  geom_vline(xintercept=1127, linetype="dashed", 
             color = "grey", size=0.3)+
  annotate(geom="text", x = 700, y=0.45, label = "Tang",size=5)+
  annotate(geom="text", x = 930, y=0.45, label = "Five", size=3)+
  annotate(geom="text", x = 930, y=0.4, label = "Dynasties", size=3)+
  annotate(geom="text", x = 1130, y=0.45, label = "Song", size=5)+
  annotate(geom="text", x = 1050, y=0.40, label = "N", size=4)+
  annotate(geom="text", x = 1170, y=0.40, label = "S", size=4)+
  theme_bw()+
  theme(legend.position="none")+
  theme(
    axis.title.x = element_text(size = 10),
    axis.text.x = element_text(size = 7),
    axis.text.y = element_text(size = 7),
    axis.title.y = element_text(size = 10))

kinproximity


